<script setup>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getPurchaseListService,
  addPurchaseService,
  updatePurchaseService,
  deletePurchaseService
} from "@/api/purchase.js";

const formRef = ref(null);
const purchases = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const purchaseForm = reactive({
  purchaseId: '',
  deviceId: '',
  quantity: '',
  unitPrice: '',
  totalAmount: '',
  purchaseDate: new Date().toISOString().split('T')[0], // 设置默认采购日期为今天
  supplier: '',
  contractNumber: '',
  purchaserId: '',
  warrantyUntil: '',
  createdAt: ''
});

const rules = reactive({
  deviceId: [{ required: true, message: '请输入设备编号', trigger: 'blur' }],
  quantity: [{ required: true, message: '请输入采购数量', trigger: 'blur' }],
  unitPrice: [{ required: true, message: '请输入单价', trigger: 'blur' }],
  totalAmount: [{ required: true, message: '请输入总金额', trigger: 'blur' }],
  purchaseDate: [{ required: true, message: '请选择采购日期', trigger: 'change' }],
  supplier: [{ required: true, message: '请输入供应商', trigger: 'blur' }],
  purchaserId: [{ required: true, message: '请输入采购人ID', trigger: 'blur' }]
});
const searchForm = reactive({
  purchaseId: '',
  deviceId: '',
  supplier: ''
});
const dialogVisible = ref(false);
const dialogTitle = ref('新增采购记录');
const isEdit = ref(false);

// 获取采购记录
const getPurchases = async (params) => {
  try {
    const res = await getPurchaseListService(params);
    if (res.code === 200) {
      purchases.value = res.data.list || [];
      total.value = res.data.total || 0;
    }
  } catch (error) {
    console.error("获取采购记录失败:", error);
  }
};

// 初始化加载数据
getPurchases({
  ...searchForm,
  pageNum: currentPage.value,
  pageSize: pageSize.value
});

// 处理页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  getPurchases({
    ...searchForm,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  });
};

// 处理页面大小变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1;
  getPurchases({
    ...searchForm,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  });
};

// 打开新增对话框
const openAddDialog = () => {
  Object.assign(purchaseForm, {
    purchaseId: '',
    deviceId: '',
    quantity: '',
    unitPrice: '',
    totalAmount: '',
    purchaseDate: new Date().toISOString().split('T')[0], // 设置默认采购日期为今天
    supplier: '',
    contractNumber: '',
    purchaserId: '',
    warrantyUntil: '',
    createdAt: ''
  });
  dialogTitle.value = '新增采购记录';
  isEdit.value = false;
  dialogVisible.value = true;
};

// 打开修改对话框
const openEditDialog = (row) => {
  Object.assign(purchaseForm, row);
  dialogTitle.value = '修改采购记录';
  isEdit.value = true;
  dialogVisible.value = true;
};

// 添加采购记录
const addPurchase = async () => {
  try {
    await formRef.value.validate(async (valid) => {
      if (!valid) return;
      const res = await addPurchaseService(purchaseForm);
      if (res.code === 200) {
      ElMessage.success('添加成功');
      dialogVisible.value = false;
      getPurchases({
        ...searchForm,
        pageNum: currentPage.value,
        pageSize: pageSize.value
      });
      }
    });
  } catch (error) {
    console.error("添加采购记录失败:", error);
  }
};

// 修改采购记录
const updatePurchase = async () => {
  try {
    await formRef.value.validate(async (valid) => {
      if (!valid) return;
      const res = await updatePurchaseService(purchaseForm);
      if (res.code === 200) {
      ElMessage.success('修改成功');
      dialogVisible.value = false;
      getPurchases({
        ...searchForm,
        pageNum: currentPage.value,
        pageSize: pageSize.value
      });
      }
    });
  } catch (error) {
    console.error("修改采购记录失败:", error);
  }
};

// 删除采购记录
const deletePurchase = (row) => {
  ElMessageBox.confirm(
      '确定要删除这条采购记录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    try {
      const res = await deletePurchaseService(row.purchaseId);
      if (res.code === 200) {
        ElMessage.success('删除成功');
         getPurchases({
          ...searchForm,
          pageNum: currentPage.value,
          pageSize: pageSize.value
        });
      }
    } catch (error) {
      console.error("删除采购记录失败:", error);
    }
  }).catch(() => {
    // 取消删除
  });
};

// 查询采购记录
const searchPurchases = () => {
  currentPage.value = 1;
  getPurchases({
    ...searchForm,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  });
};

// 格式化日期
const formatDate = (row, column, cellValue) => {
  if (!cellValue) return '';
  const date = new Date(cellValue);
  if (isNaN(date.getTime())) {
    return cellValue;
  }
  return date.toLocaleDateString();
};
</script>

<template>
  <el-text class="mx-1" style="font-size: 1.25rem">采购记录</el-text>

  <!-- 查询表单 -->
  <el-form :inline="true" @submit.prevent>
    <el-form-item label="采购编号">
      <el-input v-model="searchForm.purchaseId" placeholder="请输入采购编号"></el-input>
    </el-form-item>
    <el-form-item label="设备编号">
      <el-input v-model="searchForm.deviceId" placeholder="请输入设备编号"></el-input>
    </el-form-item>
    <el-form-item label="供应商">
      <el-input v-model="searchForm.supplier" placeholder="请输入供应商"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="searchPurchases">查询</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="success" @click="openAddDialog">新增</el-button>
    </el-form-item>
  </el-form>

  <!-- 采购记录表格 -->
  <el-table :data="purchases" style="width: 100%">
    <el-table-column prop="purchaseId" label="采购编号" width="95" />
    <el-table-column prop="deviceId" label="设备编号" width="95" />
    <el-table-column prop="quantity" label="采购数量" width="95" />
    <el-table-column prop="unitPrice" label="单价" width="95" />
    <el-table-column prop="totalAmount" label="总金额" width="95" />
    <el-table-column label="采购日期" width="95">
      <template #default="scope">
        {{ formatDate(scope.row, null, scope.row.purchaseDate) }}
      </template>
    </el-table-column>
    <el-table-column prop="supplier" label="供应商" width="95" />
    <el-table-column prop="contractNumber" label="合同编号" width="95" />
    <el-table-column prop="purchaserId" label="采购人ID" width="95" />
    <el-table-column label="保修截止日期" width="95">
      <template #default="scope">
        {{ formatDate(scope.row, null, scope.row.warrantyUntil) }}
      </template>
    </el-table-column>
    <el-table-column label="创建时间" width="95">
      <template #default="scope">
        {{ formatDate(scope.row, null, scope.row.createdAt) }}
      </template>
    </el-table-column>
    <el-table-column label="操作" width="120">
      <template #default="scope">
        <el-button type="primary" size="small" @click="openEditDialog(scope.row)">修改</el-button>
        <el-button type="danger" size="small" @click="deletePurchase(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <div class="demo-pagination-block">
    <div class="demonstration">页码</div>
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 30, 50, 100]"
        :total="total"
        layout="sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>

  <!-- 新增/修改对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form ref="formRef" :model="purchaseForm" :rules="rules" label-width="100px">
<!--      <el-form-item label="采购编号">-->
<!--        <el-input v-model="purchaseForm.purchaseId" :disabled="isEdit"></el-input>-->
<!--      </el-form-item>-->
      <el-form-item label="设备编号" prop="deviceId">
        <el-input v-model="purchaseForm.deviceId"></el-input>
      </el-form-item>
      <el-form-item label="采购数量" prop="quantity">
        <el-input v-model="purchaseForm.quantity" type="number"></el-input>
      </el-form-item>
      <el-form-item label="单价" prop="unitPrice">
        <el-input v-model="purchaseForm.unitPrice" type="number"></el-input>
      </el-form-item>
      <el-form-item label="总金额" prop="totalAmount">
        <el-input v-model="purchaseForm.totalAmount" type="number"></el-input>
      </el-form-item>
      <el-form-item label="采购日期" prop="purchaseDate">
        <el-date-picker v-model="purchaseForm.purchaseDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
      </el-form-item>
      <el-form-item label="供应商" prop="supplier">
        <el-input v-model="purchaseForm.supplier"></el-input>
      </el-form-item>
      <el-form-item label="合同编号" prop="contractNumber">
        <el-input v-model="purchaseForm.contractNumber"></el-input>
      </el-form-item>
      <el-form-item label="采购人ID" prop="purchaserId">
        <el-input v-model="purchaseForm.purchaserId"></el-input>
      </el-form-item>
      <el-form-item label="保修截止日期" prop="warrantyUntil">
        <el-date-picker v-model="purchaseForm.warrantyUntil" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="isEdit ? updatePurchase() : addPurchase()">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.demonstration {
  margin-bottom: 10px;
}
</style>
